package com.example.fengyungo.activity.login;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.example.fengyungo.R;
import com.example.fengyungo.activity.BaseActivity;
import com.example.fengyungo.activity.main.MainActivity;
import com.example.fengyungo.constant.DriverConstant;
import com.example.fengyungo.domain.Driver;
import com.example.fengyungo.utils.DriverUtils;
import com.example.fengyungo.utils.OkHttpUtils;
import com.example.fengyungo.utils.ThreadPoolUtil;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputLayout;

import java.io.IOException;
import java.util.List;

/**
 * @author XLR
 */
public class LoginActivity extends BaseActivity {

    private static final String TAG = "LoginActivity";

    /**
     * 跳过按钮
     */
    Button skip;
    /**
     * 注册按钮
     */
    Button register;
    /**
     * 登录按钮
     */
    Button login;
    /**
     * 忘记密码按钮
     */
    Button forget;
    /**
     * 用户名输入框
     */
    EditText usernameEditText;
    /**
     * 密码输入框
     */
    EditText passwordEditText;
    /**
     * 用户名处TextInputLayout
     */
    TextInputLayout inputUsername;
    /**
     * 密码处TextInputLayout
     */
    TextInputLayout inputPassword;
    /**
     * 已登录，可直接登录
     */
    boolean hasLogin;
    /**
     * 加载中
     */
    ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        progressBar = findViewById(R.id.progress_bar);

        // 判断用户是否已经登录过
        SharedPreferences preferences = getSharedPreferences(DriverConstant.SP_NAME, MODE_PRIVATE);
        hasLogin = preferences.getBoolean(DriverConstant.CAN_LOGIN, false);
        // 如果已经登录过，直接进入
        if (hasLogin) {
            Intent intentLogin = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intentLogin);
            finish();
        }

        initControl();

        skip.setOnClickListener(onClickListener);
        register.setOnClickListener(onClickListener);
        login.setOnClickListener(onClickListener);
        forget.setOnClickListener(onClickListener);

    }

    /**
     * 初始化控件
     */
    private void initControl() {
        usernameEditText = findViewById(R.id.username);
        passwordEditText = findViewById(R.id.password);

        inputUsername = findViewById(R.id.input_username);
        inputPassword = findViewById(R.id.input_password);

        skip = findViewById(R.id.skip);
        register = findViewById(R.id.register);
        login = findViewById(R.id.login);
        forget = findViewById(R.id.forget_password);
    }

    /**
     * 点击事件
     */
    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.skip:
                    Intent intent1 = new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(intent1);
                    finish();
                    break;
                case R.id.register:
                    Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                    startActivity(intent);
                    break;
                case R.id.login:
                    login(view);
                    break;
                case R.id.forget_password:
                    Snackbar.make(view, "oh,no!", Snackbar.LENGTH_LONG)
                            .show();
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 登录功能
     *
     * @param view View
     */
    private void login(View view) {
        boolean cancel = false;
        View focusView = null;

        inputUsername.setError(null);
        inputPassword.setError(null);

        // 获取输入框中的用户名，密码
        String username = usernameEditText.getText().toString();
        String password = passwordEditText.getText().toString();

        // 用户名为空
        if (username.isEmpty()) {
            inputUsername.setError(getString(R.string.input_username));
            focusView = usernameEditText;
            cancel = true;
        }
        // 密码为空
        else if (password.isEmpty()) {
            inputPassword.setError(getString(R.string.input_password));
            focusView = passwordEditText;
            cancel = true;
        }

        if (cancel) {
            // 出现错误的账号或者密码的View获得焦点
            focusView.requestFocus();
        } else {
            progressBar.setVisibility(View.VISIBLE);
            // 发送用户名、密码到后端，并获取结果
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        // 发送GET请求到后端，并接收响应数据
                        String url = DriverConstant.URL_USER_DRIVER + "/login?username=" + username + "&password=" + password;
                        String responseData = OkHttpUtils.get(url);

                        List<Driver> drivers = DriverUtils.parseDriversJsonWithJsonObject(responseData);
                        Log.d(TAG, "run: drivers:" + drivers);

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                progressBar.setVisibility(View.GONE);
                                // 登录失败的条件
                                if (drivers.size() == 0) {
                                    Toast.makeText(LoginActivity.this, getString(R.string.login_fail) + "," + getString(R.string.ac_or_pa_error), Toast.LENGTH_SHORT).show();
                                }
                                // 登录成功的条件
                                else {
                                    Driver driver = drivers.get(0);
                                    // 登录成功后将登录信息、司机信息存到SharedPreferences中
                                    SharedPreferences.Editor editor = getSharedPreferences(DriverConstant.SP_NAME, MODE_PRIVATE).edit();
                                    // 将登录信息存入SharedPreferences
                                    editor.putBoolean(DriverConstant.CAN_LOGIN, true);
                                    // 将司机信息存入SharedPreferences
                                    editor.putString(DriverConstant.ID, driver.getId());
                                    editor.putString(DriverConstant.NICKNAME, driver.getNickname());
                                    editor.putString(DriverConstant.USERNAME, driver.getUsername());
                                    editor.putString(DriverConstant.SEX, driver.getSex());
                                    editor.putString(DriverConstant.PHONE, driver.getPhone());
                                    editor.putString(DriverConstant.PASSWORD, driver.getPassword());
                                    editor.putString(DriverConstant.ID_CARD, driver.getIdCard());
                                    editor.putString(DriverConstant.AVATAR, driver.getAvatar());
                                    editor.putInt(DriverConstant.STATUS, driver.getStatus());
                                    editor.putString(DriverConstant.CREATE_TIME, driver.getCreateTime());
                                    editor.putString(DriverConstant.MAIL, driver.getMail());

                                    editor.apply();

                                    Toast.makeText(LoginActivity.this, getString(R.string.login_success), Toast.LENGTH_SHORT).show();
                                    Intent intentLogin = new Intent(LoginActivity.this, MainActivity.class);
                                    startActivity(intentLogin);
                                    finish();
                                }
                            }
                        });

                    } catch (IOException e) {
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                progressBar.setVisibility(View.GONE);
                                Toast.makeText(LoginActivity.this, getString(R.string.connection_error), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            };
            ThreadPoolUtil.execute(runnable);
        }
    }
}